package com.springbootbase.springbootproject.interceptors;

import com.springbootbase.springbootproject.pojo.Result;
import com.springbootbase.springbootproject.utils.JwtUtil;
import com.springbootbase.springbootproject.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;


@Component
public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response,Object handler) throws Exception{
//        令牌验证
       String tokens = request.getHeader("Authorization");
       try {
           Map<String, Object> claims = JwtUtil.parseToken(tokens);
           ThreadLocalUtil.set(claims);
           return true;
       }catch (Exception e){
           response.setStatus(401);
           return false;
       }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
